<template>
	<view class="container">
		<!-- 轮播图 -->
		<swiper class="banner" circular autoplay interval="3000" duration="1000" indicator-dots>
			<swiper-item v-for="(item, index) in bannerList" :key="index">
				<image :src="item.imageUrl" mode="aspectFill"></image>
			</swiper-item>
		</swiper>

		<!-- 搜索框 -->
		<view class="search-box">
			<view class="search-wrap">
				<view class="search-bar">
					<uni-icons type="search" size="16" color="#666666"></uni-icons>
					<input 
						type="text" 
						class="search-input" 
						placeholder="搜索商品" 
						:value="keyword"
						@input="handleSearchInput"
						@confirm="handleSearch"
						confirm-type="search"
					/>
					<uni-icons 
						v-if="keyword" 
						type="clear" 
						size="16" 
						color="#999999" 
						@click="clearSearch"
					></uni-icons>
				</view>
				<button class="search-btn" @click="handleSearch">搜索</button>
			</view>
		</view>

		<!-- 商品列表 -->
		<view class="goods-container">
			<scroll-view scroll-y="true" class="goods-list">
				<view v-if="isSearching" class="loading">
					<text>搜索中...</text>
				</view>
				<view v-else-if="goodsList.length === 0" class="empty">
					<image src="/static/images/empty-goods.png" mode="aspectFit"></image>
					<text>暂无相关商品</text>
				</view>
				<view v-else class="goods-grid">
					<view class="goods-item" v-for="(item, index) in goodsList" :key="index">
						<image 
							class="goods-img" 
							:src="item.cover_image ? config.baseUrl + item.cover_image : '/static/images/default-goods.png'" 
							mode="aspectFill"
						></image>
						<view class="goods-info">
							<view class="goods-title">{{item.title}}</view>
							<view class="goods-desc">{{item.desc}}</view>
							<view class="stock">库存：{{item.stock}}件</view>
							<view class="gift-rule" v-if="item.giftRules && item.giftRules.length">
								<text class="tag">赠</text>
								<text class="rule">{{item.giftRuleText}}</text>
							</view>
							<view class="price-box">
								<text class="price">￥{{item.price}}</text>
								<view class="cart-btn" v-if="userRole!=2" @click="addToCart(item)">
									<uni-icons type="cart" size="20" color="#fff"></uni-icons>
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 加入购物车弹窗 -->
		<view class="popup" v-if="showCartPopup" @click="closeCartPopup">
			<view class="popup-content" @click.stop>
				<view class="popup-header">
					<view class="goods-info">
						<image 
							:src="currentGoods.cover_image ? config.baseUrl + currentGoods.cover_image : '/static/images/default-goods.png'" 
							mode="aspectFill"
						></image>
						<view class="info">
							<view class="price">￥{{currentGoods.price}}</view>
							<view class="stock">库存：{{currentGoods.stock}}件</view>
						</view>
					</view>
					<view class="close" @click="closeCartPopup">×</view>
				</view>
				
				<view class="popup-body">
					<view class="goods-title">{{currentGoods.title}}</view>
					<view class="goods-desc">{{currentGoods.desc}}</view>
					
					<!-- 赠送规则显示 -->
					<view class="gift-rules" v-if="currentGoods.giftRules && currentGoods.giftRules.length">
						<view class="rule-item" v-for="(rule, index) in currentGoods.giftRules" :key="index">
							满{{rule.buyNum}}件送{{rule.giftNum}}件
						</view>
					</view>
					
					<view class="num-section">
						<text>下单数量</text>
						<view class="stepper">
							<view class="btn minus" :class="{ disabled: buyNum <= 1 }" @click="handleDecrease">
								<uni-icons type="minus" size="16" :color="buyNum <= 1 ? '#ccc' : '#666'"></uni-icons>
							</view>
							<input 
								type="number" 
								v-model="buyNum" 
								class="input"
								@blur="handleNumCheck"
							/>
							<view class="btn plus" @click="handleIncrease">
								<uni-icons type="plus" size="16" color="#666"></uni-icons>
							</view>
						</view>
					</view>
					
					<!-- 赠送数量显示 -->
					<view class="gift-info" v-if="giftNum > 0">
						<text class="label">赠送数量：</text>
						<text class="num">{{giftNum}}件</text>
						<text class="tip">（根据购买数量自动计算）</text>
					</view>
				</view>
				
				<view class="popup-footer">
					<button class="confirm-btn" @click="confirmAddToCart">加入购物车</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { config } from '@/utils/config.js'

// 商品列表数据
const goodsList = ref([])
// 轮播图数据
const bannerList = ref([])

// 获取轮播图数据
const getBannerList = async () => {
	try {
		const res = await uni.request({
			url: config.baseUrl + '/api/banner/list',
			method: 'GET'
		})
		
		if (res.data.code === 200) {
			bannerList.value = res.data.data.filter(item => item.status === 1)
		} else {
			throw new Error(res.data.message)
		}
	} catch (error) {
		uni.showToast({
			title: '获取轮播图失败',
			icon: 'none'
		})
	}
}

// 添加搜索相关变量和方法
const keyword = ref('')
const isSearching = ref(false)

// 修改获取商品列表方法，支持搜索
const getGoodsList = async (search = '') => {
	try {
		const url = config.baseUrl + '/api/goods/list' + (search ? `?keyword=${encodeURIComponent(search)}` : '')
		const res = await uni.request({
			url,
			method: 'GET'
		})
		
		if (res.data.code === 200) {
			goodsList.value = res.data.data
		} else {
			throw new Error(res.data.message)
		}
	} catch (error) {
		uni.showToast({
			title: '获取商品列表失败',
			icon: 'none'
		})
	} finally {
		if (isSearching.value) {
			isSearching.value = false
		}
	}
}

// 处理搜索输入
const handleSearchInput = (e) => {
	keyword.value = e.detail.value
}

// 处理搜索提交
const handleSearch = () => {
	if (!keyword.value.trim()) {
		return getGoodsList()
	}
	isSearching.value = true
	getGoodsList(keyword.value.trim())
}

// 清搜索
const clearSearch = () => {
	keyword.value = ''
	getGoodsList()
}

// 跳转搜索页
const goSearch = () => {
	uni.navigateTo({
		url: '/pages/search/index'
	})
}


// 检查登录状态
const checkLogin = () => {
	const token = uni.getStorageSync('token')
	if (!token) {
		uni.showModal({
			title: '提示',
			content: '请先登录后再操作',
			success: (res) => {
				if (res.confirm) {
					uni.navigateTo({
						url: '/pages/user/login'
					})
				}
			}
		})
		return false
	}
	return true
}

// 加入购物车
const addToCart = (item) => {
	// 检查登录状态
	if (!checkLogin()) return
	
	// 再次检查是否是管理员（以防登录后角色变化）
	if (userRole.value==2) {
		uni.showToast({
			title: '管理员不能加入购物车',
			icon: 'none'
		})
		return
	}
	
	currentGoods.value = item
	buyNum.value = 1
	giftNum.value = calculateGiftNum(1)
	showCartPopup.value = true
}

// 购物车弹窗相关
const showCartPopup = ref(false)
const currentGoods = ref({})
const buyNum = ref(1)

// 关闭弹窗
const closeCartPopup = () => {
	showCartPopup.value = false
}

// 增减数量
const handleDecrease = () => {
	if (buyNum.value > 1) {
		buyNum.value--
		giftNum.value = calculateGiftNum(buyNum.value)
	}
}

const handleIncrease = () => {
	buyNum.value++
	giftNum.value = calculateGiftNum(buyNum.value)
}

// 检查数量
const handleNumCheck = () => {
	let num = parseInt(buyNum.value)
	if (isNaN(num) || num < 1) {
		num = 1
	}
	if (num > currentGoods.value.stock) {
		num = currentGoods.value.stock
		uni.showToast({
			title: '超出库存数量',
			icon: 'none'
		})
	}
	updateBuyNum(num)
}

// 确认加入购物车
const confirmAddToCart = async () => {
	// 再次检查登录状态
	if (!checkLogin()) return
	
	// 判断购买数量
	if (buyNum.value <= 0) {
		uni.showToast({
			title: '请选择购买数量',
			icon: 'none'
		})
		return
	}

	try {
		const res = await uni.request({
			url: config.baseUrl + '/api/cart/add',
			method: 'POST',
			data: {
				goodsId: currentGoods.value.id,
				num: buyNum.value,
				giftNum: giftNum.value
			},
			header: {
				'Authorization': `Bearer ${uni.getStorageSync('token')}`,
				'Content-Type': 'application/json'
			}
		})
		
		if (res.data.code === 200) {
			uni.showToast({
				title: '已加入购物车',
				icon: 'success'
			})
			closeCartPopup()
		} else {
			throw new Error(res.data.message)
		}
	} catch (error) {
		console.error('加入购物车失败:', error)
		uni.showToast({
			title: '加入购物车失败',
			icon: 'none'
		})
	}
}

// 跳转商品详情
const goDetail = (item) => {
	uni.navigateTo({
		url: '/pages/goods/detail?id=' + item.id
	})
}

// 添加赠送数量计算
const giftNum = computed(() => {
	if (!currentGoods.value?.giftRules?.length) return 0
	
	// 按购买数量从大到小排序规则
	const sortedRules = [...currentGoods.value.giftRules].sort((a, b) => b.buyNum - a.buyNum)
	
	// 找到第一个满足条件的规则
	const matchRule = sortedRules.find(rule => buyNum.value >= rule.buyNum)
	
	return matchRule ? matchRule.giftNum : 0
})

// 修改数量时重新计算赠送数量
const updateBuyNum = (num) => {
	buyNum.value = num
	// giftNum 计算属性，会自动更新
}

// 计算赠送数量
const calculateGiftNum = (num) => {
	if (!currentGoods.value?.giftRules?.length) return 0
	
	// 按购买数量从大到小排序规则
	const rules = [...currentGoods.value.giftRules].sort((a, b) => b.buyNum - a.buyNum)
	
	// 找到第一个满足条件的规则
	const matchRule = rules.find(rule => num >= rule.buyNum)
	return matchRule ? matchRule.giftNum : 0
}

// 监听登录成功事件
onMounted(() => {
	getBannerList()
	getGoodsList()
	
	// 监听登录成功事件
	uni.$on('loginSuccess', () => {
		getGoodsList()
	})
})

// 在组件卸载时移除事件监听
onUnmounted(() => {
	uni.$off('loginSuccess')
})
const userRole = ref(uni.getStorageSync('userRole'))
// 使用 onShow 生命周期，每次显示页面时刷新数据
onShow(() => {
	// 获取最新商品列表和状态
	userRole.value = uni.getStorageSync('userRole')
	getGoodsList()
})
</script>

<style lang="scss">
	.container {
			min-height: 100vh;
			background-color: #f7f8fa;
			display: flex;
			flex-direction: column;
		}

		.banner {
			width: 100%;
			height: 300rpx;
			flex-shrink: 0;
			
			image {
				width: 100%;
				height: 100%;
			}
		}

		.search-box {
			padding: 20rpx;
			background: #fff;
			
			.search-wrap {
				display: flex;
				align-items: center;
				gap: 20rpx;
			}
			
			.search-bar {
				flex: 1;
				display: flex;
				align-items: center;
				background: #f7f8fa;
				border-radius: 32rpx;
				padding: 0 24rpx;
				height: 64rpx;
				
				.uni-icons {
					margin-right: 12rpx;
				}
				
				.search-input {
					flex: 1;
					height: 64rpx;
					font-size: 28rpx;
					color: #333;
					
					&::placeholder {
						color: #999;
					}
				}
			}
			
			.search-btn {
				width: 120rpx;
				height: 64rpx;
				background: #ff6b81;
				color: #fff;
				font-size: 28rpx;
				border-radius: 32rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				margin: 0;
				padding: 0;
				
				&:active {
					background: darken(#ff6b81, 5%);
				}
			}
		}

		.goods-container {
			flex: 1;
			overflow: hidden;

			.loading {
				text-align: center;
				padding: 40rpx 0;
				
				text {
					font-size: 28rpx;
					color: #999;
				}
			}
			
			.empty {
				display: flex;
				flex-direction: column;
				align-items: center;
				padding-top: 200rpx;
				
				image {
					width: 240rpx;
					height: 240rpx;
					margin-bottom: 30rpx;
				}
				
				text {
					font-size: 28rpx;
					color: #999;
				}
			}
		}

		.goods-list {
			height: 100%;
			padding: 20rpx;
			box-sizing: border-box;
			
			.goods-grid {
				display: flex;
				flex-wrap: wrap;
				justify-content: space-between;
				
				.goods-item {
					width: 345rpx;
					background: #fff;
					border-radius: 12rpx;
					margin-bottom: 20rpx;
					overflow: hidden;
					
					.goods-img {
						width: 100%;
						height: 345rpx;
					}
					
					.goods-info {
						padding: 16rpx;
						
						.goods-title {
							font-size: 28rpx;
							color: #333;
							font-weight: bold;
							margin-bottom: 12rpx;
							white-space: nowrap;
							overflow: hidden;
							text-overflow: ellipsis;
							line-height: 1.4;
							height: 40rpx;
						}
						
						.goods-desc {
							font-size: 24rpx;
							color: #999;
							margin-bottom: 12rpx;
							white-space: nowrap;
							overflow: hidden;
							text-overflow: ellipsis;
							line-height: 1.4;
							height: 34rpx;
						}
						
						.stock {
							font-size: 24rpx;
							color: #666;
							margin-bottom: 20rpx;
							line-height: 1.4;
							height: 34rpx;
						}
						
						.price-box {
							display: flex;
							justify-content: space-between;
							
							.price {
								font-size: 32rpx;
								color: #ff6b81;
								font-weight: bold;
							}
							
							.cart-btn {
								width: 56rpx;
								height: 56rpx;
								background: #ff6b81;
								border-radius: 28rpx;
								display: flex;
								align-items: center;
								justify-content: center;
								
								&:active {
									background: darken(#ff6b81, 5%);
								}
							}
						}
					}
				}
			}
		}

		// 弹窗样式
		.popup {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background: rgba(0,0,0,0.5);
			z-index: 999;
			
			.popup-content {
				position: absolute;
				left: 0;
				right: 0;
				bottom: 0;
				background: #fff;
				border-radius: 24rpx 24rpx 0 0;
				padding: 30rpx;
				
				.popup-header {
					display: flex;
					align-items: flex-start;
					margin-bottom: 30rpx;
					
					.goods-info {
						flex: 1;
						display: flex;
						
						image {
							width: 160rpx;
							height: 160rpx;
							border-radius: 8rpx;
							margin-right: 20rpx;
						}
						
						.info {
							.price {
								font-size: 36rpx;
								color: #ff6b81;
								font-weight: bold;
								margin-bottom: 10rpx;
							}
							
							.stock {
								font-size: 24rpx;
								color: #666;
							}
						}
					}
					
					.close {
						padding: 20rpx;
						font-size: 40rpx;
						color: #999;
						margin: -20rpx -20rpx 0 0;
					}
				}
				
				.popup-body {
					.goods-title {
						font-size: 28rpx;
						color: #333;
						font-weight: bold;
						margin-bottom: 8rpx;
					}
					
					.goods-desc {
						font-size: 24rpx;
						color: #999;
						margin-bottom: 30rpx;
					}
					
					.num-section {
						display: flex;
						justify-content: space-between;
						align-items: center;
						margin-bottom: 30rpx;
						
						text {
							font-size: 28rpx;
							color: #333;
						}
						
						.stepper {
							display: flex;
							align-items: center;
							height: 60rpx;
							border: 2rpx solid #eee;
							border-radius: 8rpx;
							
							.btn {
								width: 60rpx;
								height: 100%;
								display: flex;
								align-items: center;
								justify-content: center;
								background: #f8f8f8;
								
								&.disabled {
									background: #f5f5f5;
								}
							}
							
							.input {
								width: 80rpx;
								height: 100%;
								text-align: center;
								font-size: 28rpx;
								background: #fff;
								border-left: 2rpx solid #eee;
								border-right: 2rpx solid #eee;
							}
							
							.minus {
								border-radius: 8rpx 0 0 8rpx;
							}
							
							.plus {
								border-radius: 0 8rpx 8rpx 0;
							}
						}
					}
				}
				
				.popup-footer {
					margin-top: 40rpx;
					
					.confirm-btn {
						width: 100%;
						height: 88rpx;
						background: #ff6b81;
						color: #fff;
						font-size: 32rpx;
						border-radius: 44rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						
						&:active {
							background: darken(#ff6b81, 5%);
						}
					}
				}
			}
		}

		// 添加赠送规则样式
		.gift-rule {
			display: flex;
			align-items: center;
			margin-bottom: 10rpx;
			
			.tag {
				background: #ff6b81;
				color: #fff;
				font-size: 20rpx;
				padding: 2rpx 8rpx;
				border-radius: 4rpx;
				margin-right: 8rpx;
			}
			
			.rule {
				font-size: 24rpx;
				color: #ff6b81;
			}
		}

		// 弹窗中的赠送规则样式
		.gift-rules {
			margin-bottom: 20rpx;
			
			.rule-item {
				font-size: 24rpx;
				color: #ff6b81;
				background: #fff5f6;
				padding: 8rpx 16rpx;
				border-radius: 4rpx;
				margin-bottom: 10rpx;
				
				&:last-child {
					margin-bottom: 0;
				}
			}
		}

		// 赠送数量显示样式
		.gift-info {
			margin-top: 20rpx;
			font-size: 28rpx;
			
			.label {
				color: #666;
			}
			
			.num {
				color: #ff6b81;
				font-weight: bold;
			}
		}
	</style>
